import network
import time
#from http.client import HTTPConnection

class WiFi():
    def __init__(self, essid, password):
        self.essid = essid
        self.password = password
        self.wlan = network.WLAN(network.STA_IF)

    def connect(self, timeout=5):
        self.wlan.active(True)
        if not self.wlan.isconnected():
            print('connecting to network...')
            self.wlan.connect(self.essid, self.password)
            count = 0
            while not self.wlan.isconnected():
                time.sleep(1)
                count += 1
                if count >= timeout:
                    return False
        print('network config:', self.wlan.ifconfig())
        self.ifconfig = self.wlan.ifconfig()
        self.ip = self.ifconfig[0]
        self.mask = self.ifconfig[1]
        self.gateway = self.ifconfig[2]

    def search(self):
        li = []
        ip = self.ip.split(".")
        #print(ip)
        mask = self.mask.split(".")
        for i in range(2, 255):
            ip[3] = str(i)
            if mask[2] == 0:
                for j in range(2, 255):
                    ip[2] = str(j)
                    li.append(".".join(ip))
            else:
                #print(ip)
                li.append(".".join(ip))
        avaiable_list = []
        for ip in li:
            url = "http://" + ip + "/hello"
            name = self.check_available(url)
            if name:
                avaiable_list.append(name)
        return avaiable_list

    def check_available(self, url):
        _, _, host, path = url.split('/', 3)
        addr = socket.getaddrinfo(host, 80)[0][-1]
        s = socket.socket()
        s.connect(addr)
        data = ""
        s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
        while True:
            data = s.recv(100)
            if data:
                print(str(data, 'utf8'), end='')
            else:
                break
        s.close()
        if data == "":
            return False
        else:
            return data

    def close(self):
        self.wlan.active(False)